package Task1;

public class EmailSender implements Runnable {
	private Task1.Queue queue;
	private static int flag = 0;

	public EmailSender(Task1.Queue queue1) {
		this.queue = queue1;
	}

	public void sendNotificationEmail() {
		System.out.println("Notification email for "
				+ queue.getArrayEmail().get(0).getClient().getName()
				+ " was sent");
		System.out.println("Email for "
				+ queue.getArrayEmail().get(0).getClient().getName()
				+ " was deleted");
		queue.removeEmail();
		System.out.println("\n");

	}

	// TODO: [VY] This code too difficult to understand.
	// Generally, using inherited loops isn't good practice at all.
	// You can extract them to external methods, for ex.
	// do ... while - ok, it's not prohibited, but java dev don't like to use it
	public void run() {
		do {
			while (queue.getArrayEmail().size() == 0) {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			while (queue.getArrayEmail().size() != 0) {
				sendNotificationEmail();
			}
		} while (flag != EmailService.n);
		System.out.println("All emails was sent!");
	}

	public static void setFlag() {
		EmailSender.flag++;
	}
}
